package com.ibeeking.found.open.b.rest.service.impl;


import com.ibeeking.found.common.constants.WxCpServiceTypeConstant;
import com.ibeeking.found.common.entity.open.*;
import com.ibeeking.found.common.enums.OpenApiConfigEnum;
import com.ibeeking.found.common.enums.WxCpAppTypeEnum;
import com.ibeeking.found.common.response.ResponseCodeEnum;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.found.common.utils.UrlUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.gmc.global.api.feign.GlobalOpenFeignClient;
import com.ibeeking.found.open.api.common.param.OpenAuthCancelParam;
import com.ibeeking.found.open.api.common.param.OpenAuthParam;

import com.ibeeking.found.open.api.feign.OpenFileFeignClient;
import com.ibeeking.found.open.api.feign.GlobalOpenAuthFeignClient;
import com.ibeeking.found.open.b.rest.service.IOpenService;
import com.ibeeking.found.open.b.rest.service.IWxCpTpEventService;
import com.ibeeking.found.open.b.rest.service.mq.WxCpTpContactMsgEventHandler;
import com.ibeeking.found.open.service.common.constants.RedisKeyConstant;
import com.ibeeking.found.open.service.common.param.QueryOpenAuthInfoParam;
import com.ibeeking.found.open.service.common.vo.OpenAuthVO;
import com.ibeeking.found.open.service.common.vo.OpenAuthViewVO;
import com.ibeeking.found.open.service.common.vo.UrlVO;
import com.ibeeking.found.open.service.config.OpenAuthCallBackConfig;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.file.oss.dto.OssPolicyDto;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.file.FileUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpTpPermanentCodeInfo;
import me.chanjar.weixin.cp.bean.message.*;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.constant.WxCpTpConsts;
import me.chanjar.weixin.cp.message.WxCpMessageHandler;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import me.chanjar.weixin.cp.util.crypto.WxCpTpCryptUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;


/**
 * @ClassName WxCpTpEventServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-06-18 12:21
 **/
@Service("wxCpTPEventServiceImpl")
public class WxCpTpEventServiceImpl implements IWxCpTpEventService {
    private static final Logger log = LoggerFactory.getLogger(WxCpTpEventServiceImpl.class);

    private static final Integer EXPIRE_TIME = 7000; // 100分钟

    private static final Map<String, WxCpMessageRouter> wxCpMessageRouterMap = new Hashtable();

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private OpenFileFeignClient openFileFeignClient;

    @Resource
    private IOpenService openServiceImpl;

    @Resource
    private GlobalOpenAuthFeignClient globalOpenAuthFeignClient;

    @Resource
    private GlobalOpenFeignClient globalOpenFeignClient;

    @Resource
    private OpenAuthCallBackConfig openAuthCallBackConfig;

    @Resource
    private WxCpTpContactMsgEventHandler wxCpTpContactMsgEventHandler;

    @Override
    public String authWxCpTpTicket(HttpServletRequest request, HttpServletResponse response, String signature, String timestamp, String nonce, String echostr) {
        try {

            WxCpTpService wxCpTpService = openServiceImpl.getDefaultWxCpTpService();
            if (wxCpTpService == null)  throw new BusinessException("获取企微服务失败!");
            WxCpTpConfigStorage wxCpTpConfigStorage = wxCpTpService.getWxCpTpConfigStorage();

            WxCpTpCryptUtil cryptUtil = new WxCpTpCryptUtil(wxCpTpConfigStorage);
            String encryptedXml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);

            String inMessage = cryptUtil.decryptXml(signature, timestamp, nonce, encryptedXml);
            if(inMessage == null) return "success";

            WxCpTpXmlMessage wxCpTpXmlMessage = WxCpTpXmlMessage.fromXml(inMessage);
            Map<String, Object> jsonObject = wxCpTpXmlMessage.getAllFieldsMap();
            String out = null;
            if(WxCpTpConsts.InfoType.SUITE_TICKET.equals(wxCpTpXmlMessage.getInfoType())) {
                String suitId = wxCpTpXmlMessage.getSuiteId();
                String suiteTicket = wxCpTpXmlMessage.getSuiteTicket();

                Long timeStamp = Long.getLong(wxCpTpXmlMessage.getTimeStamp());
                LogUtils.info("\nSUITE_TICKET：\n{} ", JsonUtils.toJsonStr(wxCpTpXmlMessage));
                wxCpTpConfigStorage.updateSuiteTicket(suiteTicket, 20*60);
                redisUtils.set(RedisKeyConstant.WX_CP_TP_SUITE_TICKET + suitId,suiteTicket,20*60);
                checkAndUpdateSuiteToken(wxCpTpService, suitId, signature, timestamp, nonce);
                checkAndUpdateAuthorizeAccessToken(wxCpTpService, suitId, signature, timestamp, nonce);
            } else if(WxCpTpConsts.InfoType.CREATE_AUTH.equals(wxCpTpXmlMessage.getInfoType())){
                String suiteId = wxCpTpXmlMessage.getSuiteId();
                String authCorpId = wxCpTpXmlMessage.getAuthCorpId();
                String timeStamp = wxCpTpXmlMessage.getTimeStamp();
                OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());
                if (null == wxOpenConfigDTO) {
                    throw new BusinessException("无法获取开发平台参数信息");
                }
                OpenAuthCancelParam param = new OpenAuthCancelParam();
                param.setOpenAppId(wxOpenConfigDTO.getOpenAppId());
                param.setAppId(authCorpId);
                param.setComponentAppId(suiteId);
                globalOpenAuthFeignClient.cancelAuth(param);
            } else if(WxCpTpConsts.InfoType.CHANGE_AUTH.equals(wxCpTpXmlMessage.getInfoType())){
                String suiteId = wxCpTpXmlMessage.getSuiteId();
                String authCode = wxCpTpXmlMessage.getAuthCode();
                String timeStamp = wxCpTpXmlMessage.getTimeStamp();
                LogUtils.info("\nCHANGE_AUTH：\n{} ", JsonUtils.toJsonStr(wxCpTpXmlMessage));

            } else if(WxCpTpConsts.InfoType.CANCEL_AUTH.equals(wxCpTpXmlMessage.getInfoType())){
                String suiteId = wxCpTpXmlMessage.getSuiteId();
                String authCorpId = wxCpTpXmlMessage.getAuthCorpId();
                String timeStamp = wxCpTpXmlMessage.getTimeStamp();
                OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());
                if (null == wxOpenConfigDTO) {
                    throw new BusinessException("无法获取开发平台参数信息");
                }
                OpenAuthCancelParam param = new OpenAuthCancelParam();
                param.setOpenAppId(wxOpenConfigDTO.getOpenAppId());
                param.setAppId(authCorpId);
                param.setComponentAppId(suiteId);

                globalOpenAuthFeignClient.cancelAuth(param);

            }  else if(WxCpTpConsts.InfoType.CHANGE_CONTACT.equals(wxCpTpXmlMessage.getInfoType())){
                if (StringUtils.isEmpty(wxCpTpXmlMessage.getChangeType())){
                    throw new Exception("该类型通讯录变更不存在");
                }
                if("create_user".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======create_user========" );
                }else if("update_user".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======update_user========" );
                }else if("delete_user".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======delete_user========" );
                }else if("create_party".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======create_party========" );
                }else if("update_party".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======update_party========" );
                }else if("delete_party".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======delete_party========" );
                }else if("update_tag".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======update_tag========" );
                }
            }else if(WxCpTpConsts.InfoType.CHANGE_EXTERNAL_CONTACT.equals(wxCpTpXmlMessage.getInfoType())){
                if (StringUtils.isEmpty(wxCpTpXmlMessage.getChangeType())){
                    throw new Exception("该类型外部联系人通讯录变更不存在");
                }
                if("add_external_contact".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======create_user========" );
                }else if("edit_external_contact".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======edit_external_contact========" );
                }else if("del_external_contact".equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                    LogUtils.info("=======del_external_contact========" );
                }
            }

            return "success";
        }catch(Exception ex){
            return "success";
        }

    }

    @Override
    public Object msgWxCpTpEvent(HttpServletRequest request, HttpServletResponse response, String signature, String timestamp, String nonce, String echostr) {
       try {
           WxCpTpService wxCpTpService = openServiceImpl.getDefaultWxCpTpService();
           if (wxCpTpService == null) {
               throw new BusinessException("获取企微服务失败!");
           }
           WxCpTpConfigStorage wxCpTpConfigStorage = wxCpTpService.getWxCpTpConfigStorage();
           WxCpTpCryptUtil cryptUtil = new WxCpTpCryptUtil(wxCpTpConfigStorage);
           String inMessage = cryptUtil.decryptXml(signature, timestamp, nonce, IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8));
           if(inMessage == null) return "success";
           LogUtils.info("msgCpEvent:消息解密后内容为：\n{} ", JsonUtils.toJsonStr(inMessage));

           WxCpTpXmlMessage wxCpTpXmlMessage = WxCpTpXmlMessage.fromXml(inMessage);
           if(WxCpTpConsts.InfoType.CHANGE_CONTACT.equalsIgnoreCase(wxCpTpXmlMessage.getEvent())){
               if(WxCpConsts.ContactChangeType.CREATE_PARTY.equalsIgnoreCase(wxCpTpXmlMessage.getChangeType())){
                   wxCpTpContactMsgEventHandler.processCreateDepartmentMsgEvent(wxCpTpXmlMessage);
               }
           }
           if(WxCpTpConsts.InfoType.CREATE_AUTH.equals(wxCpTpXmlMessage.getInfoType())) {
               String suiteId = wxCpTpXmlMessage.getSuiteId();
               String authCorpId = wxCpTpXmlMessage.getAuthCorpId();
               String timeStamp = wxCpTpXmlMessage.getTimeStamp();
               OpenAuthDTO wxOpenAuthDTO = queryWxOpenAuthListByComponentIdAndAppId(suiteId, authCorpId);
               if (null == wxOpenAuthDTO) {
                   throw new BusinessException("无法获取开发平台参数信息");
               }
               LogUtils.info("\nCREATE_AUTH：\n{} ", JsonUtils.toJsonStr(wxCpTpXmlMessage));
           }
           return "success";
       }catch(Exception ex){
           return "";
       }

    }

    private WxCpMessageRouter getWxCpMessageRouterByAppid(String agentId) {
        WxCpMessageRouter wxCpMessageRouter = wxCpMessageRouterMap.get(agentId);
//        if (wxCpMessageRouter == null) {
//            synchronized (wxCpMessageRouterMap) {
//                wxCpMessageRouter = wxCpMessageRouterMap.get(agentId);
//                if (wxCpMessageRouter == null) {
//                    wxCpMessageRouter = new WxCpMessageRouter(openServiceImpl.getWxCpService());
//                    wxCpMessageRouterMap.put(agentId, wxCpMessageRouter);
//                    addTxtMsgRouter(agentId, wxCpMessageRouter);
//                    addEventRouter(agentId, wxCpMessageRouter);
//                }
//            }
//        }
        return wxCpMessageRouter;
    }

    private void addEventRouter(final String appId, WxCpMessageRouter wxCpMessageRouter) {
        WxCpMessageHandler handler = new WxCpMessageHandler() {
            public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
                WxCpXmlOutTextMessage m = null;
                // 订阅事件
                if (wxMessage.getEvent().equals(WxConsts.EventType.SUBSCRIBE)) {
                    if (wxMessage.getEventKey().startsWith("qrscene_") && wxMessage.getTicket() != null) {
                        String msg = wxMessage.getContent().replace("QUERY_AUTH_CODE:", "") + "_from_api";
                        WxCpMessage kefuMessage = WxCpMessage.TEXT().content(msg).toUser(wxMessage.getFromUserName()).build();
                        wxCpService.getMessageService().send(kefuMessage);
                    }
                } else if (wxMessage.getEvent().equals(WxConsts.EventType.SCAN)) {
                    // 扫码 用户已关注时的事件推送
                    if (wxMessage.getEventKey() != null || wxMessage.getTicket() != null) {
                        String msg = wxMessage.getContent().replace("QUERY_AUTH_CODE:", "") + "_from_api";
                        WxCpMessage kefuMessage = WxCpMessage.TEXT().content(msg).toUser(wxMessage.getFromUserName()).build();
                        wxCpService.getMessageService().send(kefuMessage);
                    }
                } else if (wxMessage.getEvent().equals(WxConsts.EventType.CLICK)) {// 自定义菜单点击事件
                    if (wxMessage.getEventKey() != null && !wxMessage.getEventKey().equals("")) {
                        System.out.println("事件KEY值，与自定义菜单接口中KEY值对应");
                    }
                } else if (wxMessage.getEvent().equals(WxConsts.EventType.VIEW)) {
                    System.out.println("点击菜单跳转链接时的事件推送");
                }
                return m;
            }
        };
        wxCpMessageRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).handler(handler).end();
    }

    private void addTxtMsgRouter(final String appId, WxCpMessageRouter wxCpMessageRouter) {
        WxCpMessageHandler handler = new WxCpMessageHandler() {
            public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
                                            WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
                WxCpXmlOutTextMessage m = null;
                String keys = wxMessage.getContent();
                if (keys.startsWith("xxxxx")&& wxMessage.getFromUserName().equals("DSFGDFNMHJJHJ")) {
                    String msg = wxMessage.getContent().replace("QUERY_AUTH_CODE:", "") + "_from_api";
                    WxCpMessage wxCpMessage = WxCpMessage.TEXT().content(msg).toUser(wxMessage.getFromUserName()).build();
                    wxCpService.getMessageService().send(wxCpMessage);
                }
                return m;
            }
        };
        wxCpMessageRouter.rule().async(false).msgType(WxConsts.XmlMsgType.TEXT).handler(handler).end();
    }

    /**
     * 授权注册页面扫码授权   显示二维码
     *
     * @param request
     * @return
     * @throws Exception
     * @Author ibeeking
     */
    @Override
    public UrlVO getWxCpTpPreAuthUrl(HttpServletRequest request) throws Exception {
        OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());
        DataUtils.trueThrowException(wxOpenConfigDTO == null, "系统异常:微信第三放平台appId为空!");
        String openAppId =  wxOpenConfigDTO.getOpenAppId();
        String suiteId = wxOpenConfigDTO.getComponentAppId();
        String wxOpenCpTpAuthRedirectUrl = openAuthCallBackConfig.getWxOpenCpTpAuthRedirectUrl();
        String tenantId = UserUtils.getTenantId();
        DataUtils.trueThrowException(StringUtils.isBlank(wxOpenCpTpAuthRedirectUrl), "微信第三方授权后的跳转页面尚未配置!");

        WxCpTpService wxCpTpService = openServiceImpl.getDefaultWxCpTpService();
        if(null == wxCpTpService) throw new BusinessException("企业微信服务初始化还未完成，请稍候再试");
        WxCpTpConfigStorage configStorage = wxCpTpService.getWxCpTpConfigStorage();
        LogUtils.info("========WxCpTpConfigStorage：{}========", JsonUtils.toJsonStr(configStorage));
        String suiteTicket = configStorage.getSuiteTicket();
        if(StringUtils.isEmpty(suiteTicket)){
            String suiteTicketredis = redisUtils.getString(RedisKeyConstant.WX_CP_TP_SUITE_TICKET + suiteId);
            if(StringUtils.isNotEmpty(suiteTicketredis)) {
                configStorage.updateSuiteTicket(suiteTicketredis, 1200);
            }
        }
        String suiteAccessToken = configStorage.getSuiteAccessToken();
        if(StringUtils.isEmpty(suiteAccessToken)){
            Object suiteAccessObj = redisUtils.get(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN + suiteId);
            if(ObjectUtils.isNotEmpty(suiteAccessObj)) {
                WxAccessToken oldSuiteAccessTokenEntity = (WxAccessToken)suiteAccessObj;
                configStorage.updateSuiteAccessToken(oldSuiteAccessTokenEntity);
            }
        }
        wxOpenCpTpAuthRedirectUrl = wxOpenCpTpAuthRedirectUrl + "?openAppId=" + openAppId + "&suiteId=" + suiteId + "&type=" + WxCpServiceTypeConstant.CP_TYPE_TP;


        String url = wxCpTpService.getPreAuthUrl(wxOpenCpTpAuthRedirectUrl, tenantId, 1);
        //String result = wxCpTpService.get(url,null);
        LogUtils.info("========CallBack result：{}========", JsonUtils.toJsonStr(url));
        return new UrlVO().setUrl(url);
    }


    /**
     * 获取永久授权码
     *
     * @param queryParam
     * @return
     * @throws Exception
     * @Author ibeeking
     */
    @Override
    public OpenAuthViewVO getWxCpTpPermanentAuthInfo(QueryOpenAuthInfoParam queryParam) throws Exception {
        LogUtils.info("========queryParam：{}========", JsonUtils.toJsonStr(queryParam));
        if(queryParam == null) throw new BusinessException("无法读取查询参数信息");
        OpenAuthViewVO openAuthViewVO = new OpenAuthViewVO();
        String authCode = queryParam.getAuthCode();
        if(StringUtils.isEmpty(authCode)) throw new BusinessException("获取临时授权码空");

        OssPolicyDto  ossPolicyDto = getOssFilePolicy();
        String tenantId = queryParam.getTenantId();
        String state = queryParam.getState();
        String suiteId = queryParam.getComponentAppId();
        String preAuthCodeExpiredIn = queryParam.getExpiresIn();

        OpenAuthParam param = new OpenAuthParam();
        OpenAuthOfExtend openAuthOfExtend = new OpenAuthOfExtend();
        if(StringUtils.isEmpty(tenantId)){
            tenantId = state;
        }
        if(StringUtils.isNotEmpty(tenantId)) {
            param.setTenantId(Long.valueOf(tenantId));
        }

        OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());

        DataUtils.trueThrowException(wxOpenConfigDTO == null, "系统异常:微信第三放平台appId为空!");
        LogUtils.info("========wxOpenConfigDTO：{}========", JsonUtils.toJsonStr(wxOpenConfigDTO));
        String openAppId =  wxOpenConfigDTO.getOpenAppId();
        String suiteAppId = wxOpenConfigDTO.getComponentAppId();
        param.setOpenId(wxOpenConfigDTO.getId());
        param.setConfigType(wxOpenConfigDTO.getType());
        param.setConfigSubType(wxOpenConfigDTO.getSubType());
        param.setOpenAppId(openAppId);
        param.setComponentAppId(suiteAppId);
        param.setComponentAppSecret(wxOpenConfigDTO.getComponentSecret());
        param.setAppToken(wxOpenConfigDTO.getComponentMsgToken());
        param.setAppAesKey(wxOpenConfigDTO.getComponentMsgAesKey());
        param.setAppType(WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());
        WxCpTpService wxCpTpService = openServiceImpl.getDefaultWxCpTpService();
        if(null == wxCpTpService) throw new BusinessException("企业微信服务初始化还未完成，请稍候再试");
        WxCpTpConfigStorage configStorage = wxCpTpService.getWxCpTpConfigStorage();
        String suiteTicket = configStorage.getSuiteTicket();
        if(StringUtils.isEmpty(suiteTicket)){
            String suiteTicketObj = redisUtils.getString(RedisKeyConstant.WX_CP_TP_SUITE_TICKET + suiteAppId);
            if(ObjectUtils.isNotEmpty(suiteTicketObj)) {
                configStorage.updateSuiteTicket(suiteTicketObj, 1200);
            }
        }

        OpenAuthOfWxCpTp openAuthOfWxCpTp = new OpenAuthOfWxCpTp();
        openAuthOfWxCpTp.setSuiteTicket(configStorage.getSuiteTicket());
        openAuthViewVO = BeanUtil.convertBean(param, OpenAuthViewVO.class);
        WxAccessToken suiteAccessTokenEntity = wxCpTpService.getSuiteAccessTokenEntity(true);
        if(suiteAccessTokenEntity != null) {
            openAuthOfWxCpTp.setSuiteAccessToken(suiteAccessTokenEntity.getAccessToken());
            openAuthOfWxCpTp.setSuiteAccessExpirein(System.currentTimeMillis() + suiteAccessTokenEntity.getExpiresIn() * 1000);
            openAuthOfWxCpTp.setSuiteAccessExpireTime(suiteAccessTokenEntity.getExpiresIn());
            redisUtils.set(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN + suiteAppId, suiteAccessTokenEntity, EXPIRE_TIME.intValue());
            redisUtils.set(RedisKeyConstant.WX_CP_TP_EXPIRE_IN + suiteId, System.currentTimeMillis() + suiteAccessTokenEntity.getExpiresIn() * 1000);
        }

        openAuthOfWxCpTp.setPreAuthCode(authCode);
        WxCpTpPermanentCodeInfo wxCpTpPermanentCodeInfo = wxCpTpService.getPermanentCodeInfo(authCode);
        LogUtils.info("========wxCpTpPermanentCodeInfo：{}========", JsonUtils.toJsonStr(wxCpTpPermanentCodeInfo));
        String permanentCode  = wxCpTpPermanentCodeInfo.getPermanentCode();
        redisUtils.set(RedisKeyConstant.WX_CP_TP_PERMANENT_CODE + suiteAppId, permanentCode, EXPIRE_TIME);
        openAuthOfWxCpTp.setPermanentCode(permanentCode);
        WxCpTpPermanentCodeInfo.AuthCorpInfo rtnAuthCorpInfo = wxCpTpPermanentCodeInfo.getAuthCorpInfo();

        //授权企业信息
        if(rtnAuthCorpInfo != null) {
            String authCorpId = rtnAuthCorpInfo.getCorpId();
            OpenAuthOfWxCpTpAuthCorpInfo authCorpInfo = BeanUtil.convertBean(rtnAuthCorpInfo, OpenAuthOfWxCpTpAuthCorpInfo.class);
            authCorpInfo.setCorpid(authCorpId);
            param.setAppId(authCorpId);
            openAuthViewVO.setAppId(authCorpId);
            openAuthViewVO.setName(authCorpInfo.getCorpName());
            if(StringUtils.isNotEmpty(rtnAuthCorpInfo.getCorpRoundLogoUrl())) {
                try {
                    String fileName = (String.valueOf(System.currentTimeMillis())).concat("_".concat(rtnAuthCorpInfo.getCorpId()).concat("_roundLogo.png"));
                    String fileTag = ossPolicyDto.getDir() + fileName;
                    MultipartFile multipartFile = FileUtils.getMultipartFile(rtnAuthCorpInfo.getCorpRoundLogoUrl(), fileName, fileTag);
                    ResponseResult<String> responseResult = openFileFeignClient.uploadFile(multipartFile);
                    String fileUploadPath = responseResult.getData();
                    authCorpInfo.setCorpRoundLogoUrl(UrlUtils.removeUrlDomainName(fileUploadPath));
                } catch (Exception ex) {
                    authCorpInfo.setCorpRoundLogoUrl("");
                }
            }

            if(StringUtils.isNotEmpty(rtnAuthCorpInfo.getCorpSquareLogoUrl())) {
                try {
                    String fileName = (String.valueOf(System.currentTimeMillis())).concat("_".concat(rtnAuthCorpInfo.getCorpId()).concat("_squareLogo.png"));
                    String fileTag = ossPolicyDto.getDir() + fileName;
                    MultipartFile multipartFile = FileUtils.getMultipartFile(rtnAuthCorpInfo.getCorpSquareLogoUrl(), fileName, fileTag);
                    ResponseResult<String> responseResult = openFileFeignClient.uploadFile(multipartFile);
                    String fileUploadPath = responseResult.getData();
                    authCorpInfo.setCorpSquareLogoUrl(UrlUtils.removeUrlDomainName(fileUploadPath));
                } catch (Exception ex) {
                    authCorpInfo.setCorpSquareLogoUrl("");
                }
            }

            if(StringUtils.isNotEmpty(rtnAuthCorpInfo.getCorpWxQrcode())) {
                try {
                    String fileName = (String.valueOf(System.currentTimeMillis())).concat("_".concat(rtnAuthCorpInfo.getCorpId()).concat("_qrcode.png"));
                    String fileTag = ossPolicyDto.getDir() + fileName;
                    MultipartFile multipartFile = FileUtils.getMultipartFile(rtnAuthCorpInfo.getCorpWxQrcode(), fileName, fileTag);
                    ResponseResult<String> responseResult = openFileFeignClient.uploadFile(multipartFile);
                    String fileUploadPath = responseResult.getData();
                    authCorpInfo.setCorpWxqrcode(UrlUtils.removeUrlDomainName(fileUploadPath));
                } catch (Exception ex) {
                    authCorpInfo.setCorpWxqrcode("");
                }
            }
            openAuthOfWxCpTp.setAuthCorpInfo(authCorpInfo);
            WxAccessToken corpAccessTokenEntity = wxCpTpService.getCorpToken(authCorpId,permanentCode, true);
            if(corpAccessTokenEntity != null ){
                String corpAccessToken = corpAccessTokenEntity.getAccessToken();
                if(StringUtils.isNotEmpty(corpAccessToken)){
                    openAuthOfWxCpTp.setCorpAccessToken(corpAccessToken);
                    openAuthOfWxCpTp.setCorpAccessExpireTime(corpAccessTokenEntity.getExpiresIn());
                    openAuthOfWxCpTp.setCorpAccessExpirein(System.currentTimeMillis() + corpAccessTokenEntity.getExpiresIn() * 1000);
                    redisUtils.set(RedisKeyConstant.WX_CP_TP_CORP_ACCESS.concat(suiteAppId).concat(":").concat(authCorpId), corpAccessTokenEntity, EXPIRE_TIME.intValue());
                }
            }
        }
        // 授权信息
        WxCpTpPermanentCodeInfo.AuthInfo auThInfo = wxCpTpPermanentCodeInfo.getAuthInfo();
        if(auThInfo != null) {
            List<OpenAuthOfWxCpTpAuthAgentInfo> authAgentInfos = new ArrayList<>();
            List<WxCpTpPermanentCodeInfo.Agent> agentList = auThInfo.getAgents();
            if(Collections3.isNotEmpty(agentList)) {
                agentList.stream().forEach(d->{
                    Integer agentId = d.getAgentId();
                    OpenAuthOfWxCpTpAuthAgentInfo authAgentInfo = new OpenAuthOfWxCpTpAuthAgentInfo();
                    authAgentInfo.setAgentid(agentId);
                    authAgentInfo.setName(d.getName());
                    authAgentInfo.setAuthMode(d.getAuthMode());
                    authAgentInfo.setAppid(d.getAppid());
                    authAgentInfo.setIsCustomizedApp(d.getIsCustomizedApp());

                    WxCpTpPermanentCodeInfo.Privilege privilege = d.getPrivilege();
                    if(privilege!=null) {
                        authAgentInfo.setLevel(privilege.getLevel());
                        List<Integer> allowParties = privilege.getAllowParties();
                        if(Collections3.isNotEmpty(allowParties)) {
                            authAgentInfo.setAllowParty(JsonUtils.toJsonStr(allowParties));
                        }
                        List<Integer> allowTags = privilege.getAllowTags();
                        if(Collections3.isNotEmpty(allowTags)) {
                            authAgentInfo.setAllowTag(JsonUtils.toJsonStr(allowTags));
                        }
                        List<String> allowUsers = privilege.getAllowUsers();
                        if(Collections3.isNotEmpty(allowUsers)) {
                            authAgentInfo.setAllowUser(JsonUtils.toJsonStr(allowUsers));
                        }
                        List<Integer> extraParties = privilege.getExtraParties();
                        if(Collections3.isNotEmpty(extraParties)) {
                            authAgentInfo.setExtraParty(JsonUtils.toJsonStr(extraParties));
                        }
                        List<Integer> extraTags = privilege.getExtraTags();
                        if(Collections3.isNotEmpty(extraTags)) {
                            authAgentInfo.setExtraTag(JsonUtils.toJsonStr(extraTags));
                        }
                        List<String> extraUsers = privilege.getExtraUsers();
                        if(Collections3.isNotEmpty(extraUsers)) {
                            authAgentInfo.setExtraUser(JsonUtils.toJsonStr(extraUsers));
                        }
                    }
                    if(StringUtils.isNotEmpty(d.getSquareLogoUrl())) {
                        try {
                            String fileName = (String.valueOf(System.currentTimeMillis())).concat("_".concat(agentId.toString()).concat("_square.png"));
                            String fileTag = ossPolicyDto.getDir() + fileName;
                            MultipartFile multipartFile = FileUtils.getMultipartFile(d.getSquareLogoUrl(), fileName, fileTag);
                            ResponseResult<String> responseResult = openFileFeignClient.uploadFile(multipartFile);
                            String fileUploadPath = responseResult.getData();
                            authAgentInfo.setSquareLogoUrl(UrlUtils.removeUrlDomainName(fileUploadPath));
                        } catch (Exception ex) {
                            authAgentInfo.setSquareLogoUrl("");
                        }
                    }
                    if(StringUtils.isNotEmpty(d.getRoundLogoUrl())) {
                        try {
                            String fileName = (String.valueOf(System.currentTimeMillis())).concat("_".concat(agentId.toString()).concat("_round.png"));
                            String fileTag = ossPolicyDto.getDir() + fileName;
                            MultipartFile multipartFile = FileUtils.getMultipartFile(d.getRoundLogoUrl(), fileName, fileTag);
                            ResponseResult<String> responseResult = openFileFeignClient.uploadFile(multipartFile);
                            String fileUploadPath = responseResult.getData();
                            authAgentInfo.setRoundLogoUrl(UrlUtils.removeUrlDomainName(fileUploadPath));
                        } catch (Exception ex) {
                            authAgentInfo.setRoundLogoUrl("");
                        }
                    }
                    authAgentInfos.add(authAgentInfo);
                });
                openAuthOfWxCpTp.setAuthAgentInfos(authAgentInfos);
            }
        }
        // 授权管理员信息
        WxCpTpPermanentCodeInfo.AuthUserInfo rtnAuthUserInfo = wxCpTpPermanentCodeInfo.getAuthUserInfo();
        if(rtnAuthUserInfo!=null){
            OpenAuthOfWxCpTpAuthUserInfo wxCpTpAuthUserInfo = BeanUtil.convertBean(rtnAuthUserInfo, OpenAuthOfWxCpTpAuthUserInfo.class);
            String userAvatar = rtnAuthUserInfo.getAvatar();
            if(StringUtils.isNotEmpty(userAvatar)) {
                try {
                    String fileName = (String.valueOf(System.currentTimeMillis())).concat("_".concat(rtnAuthUserInfo.getName()).concat("_avatar.png"));
                    String fileTag = ossPolicyDto.getDir() + fileName;
                    MultipartFile multipartFile = FileUtils.getMultipartFile(userAvatar, fileName, fileTag);
                    ResponseResult<String> responseResult = openFileFeignClient.uploadFile(multipartFile);
                    String fileUploadPath = responseResult.getData();
                    wxCpTpAuthUserInfo.setAvatar(UrlUtils.removeUrlDomainName(fileUploadPath));
                } catch (Exception ex) {
                    wxCpTpAuthUserInfo.setAvatar("");
                }
            }
            openAuthOfWxCpTp.setAuthUserInfo(wxCpTpAuthUserInfo);
        }
        openAuthOfExtend.setOpenAuthOfWxCpTp(openAuthOfWxCpTp);
        param.setOpenAuthOfExtend(openAuthOfExtend);
        LogUtils.info("========param：{}========", JsonUtils.toJsonStr(param));
        globalOpenAuthFeignClient.modifyAuth(param);
        openAuthViewVO.setHasOpenAuth(true);
        return openAuthViewVO;//new UrlVO().setUrl(wxOpenCpTpAuthRedirectUrl);
    }

    private WxCpXmlOutMessage route(Integer agentId, WxCpXmlMessage message) {

        return null;
    }

    @Override
    public OpenAuthVO queryWxCpTpOpenAuthInfo()  {
        Long tenantId = UserUtils.getTenantID();
        if(tenantId == null){
            DataUtils.trueThrowException(true, "获取租户tenantId失败:" + tenantId);
        }

        OpenAuthDTO wxOpenAuthDTO = queryWxOpenAuthByType(tenantId, WxCpServiceTypeConstant.CP_TYPE_TP);
        if (null != wxOpenAuthDTO) {
            OpenAuthVO openAuthVO = BeanUtil.convertBean(wxOpenAuthDTO, OpenAuthVO.class);
            OpenAuthOfExtend openAuthOfExtend = wxOpenAuthDTO.getOpenAuthOfExtend();
            if(openAuthOfExtend!=null) {
                OpenAuthOfWxCpTp openAuthOfWxCpTp = openAuthOfExtend.getOpenAuthOfWxCpTp();
                if(openAuthOfWxCpTp!=null) {
                    OssPolicyDto ossPolicyDto = getOssPolicy();
                    if (null != ossPolicyDto) {
                        OpenAuthOfWxCpTpAuthCorpInfo authCorpInfo = openAuthOfWxCpTp.getAuthCorpInfo();
                        String dnsHost = ossPolicyDto.getHost();
                        if (StringUtils.isNotEmpty(authCorpInfo.getCorpSquareLogoUrl())) {
                            authCorpInfo.setCorpSquareLogoUrl(dnsHost + "/" + authCorpInfo.getCorpSquareLogoUrl());
                        }
                        if (StringUtils.isNotEmpty(authCorpInfo.getCorpWxqrcode())) {
                            authCorpInfo.setCorpWxqrcode(dnsHost + "/" + authCorpInfo.getCorpWxqrcode());
                        }
                    }
                    openAuthVO.setHasOpenAuth(openAuthOfWxCpTp.getCorpAccessToken()!=null);
                }
            }
            openAuthVO.setOpenAuthOfExtend(openAuthOfExtend);
            return openAuthVO;
        } else {
            OpenAuthVO openAuthVO = new OpenAuthVO();
            openAuthVO.setTenantId(tenantId);
            OpenAuthOfExtend openAuthOfExtend = new OpenAuthOfExtend();
            OpenAuthOfWxCpTp openAuthOfWxCpTp = new OpenAuthOfWxCpTp();
            openAuthOfWxCpTp.setAuthCorpInfo(new OpenAuthOfWxCpTpAuthCorpInfo());
            openAuthOfWxCpTp.setAuthAgentInfos(new ArrayList<>());
            openAuthOfWxCpTp.setAuthUserInfo(new OpenAuthOfWxCpTpAuthUserInfo());
            openAuthOfExtend.setOpenAuthOfWxCpTp(openAuthOfWxCpTp);
            openAuthVO.setOpenAuthOfExtend(openAuthOfExtend);
            openAuthVO.setHasOpenAuth(openAuthOfWxCpTp.getCorpAccessToken()!=null);
            return openAuthVO;
        }
    }

    private void checkAndUpdateSuiteToken(WxCpTpService wxCpTpService, String suiteId, String signature, String timestamp, String nonce){
        WxCpTpConfigStorage wxCpTpConfigStorage = wxCpTpService.getWxCpTpConfigStorage();
        Object objSuiteAccessTokenEntity = redisUtils.get(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN.concat(suiteId));
        if(ObjectUtils.isNotEmpty(objSuiteAccessTokenEntity)) {
            Long oldExpiresIn = redisUtils.getLong(RedisKeyConstant.WX_CP_TP_EXPIRE_IN.concat(suiteId));
            if(oldExpiresIn == null) oldExpiresIn =  System.currentTimeMillis();
            if ((oldExpiresIn - System.currentTimeMillis()) <= 600*1000) {
                try {
                    WxAccessToken newSuiteAccessTokenEntity = wxCpTpService.getSuiteAccessTokenEntity(true);
                    if (newSuiteAccessTokenEntity != null) {
                        wxCpTpConfigStorage.updateSuiteAccessToken(newSuiteAccessTokenEntity);
                        redisUtils.set(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN.concat(suiteId), newSuiteAccessTokenEntity, EXPIRE_TIME.intValue());
                        redisUtils.set(RedisKeyConstant.WX_CP_TP_EXPIRE_IN.concat(suiteId), System.currentTimeMillis() + newSuiteAccessTokenEntity.getExpiresIn() * 1000);
                    }
                } catch (WxErrorException ex) {
                    throw new BusinessException("获取suiteAccessToken 出错");
                }
            }
        }else{
            try {
                WxAccessToken newSuiteAccessTokenEntity = wxCpTpService.getSuiteAccessTokenEntity(true);
                if (newSuiteAccessTokenEntity != null) {
                    wxCpTpConfigStorage.updateSuiteAccessToken(newSuiteAccessTokenEntity);
                    redisUtils.set(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN.concat(suiteId), newSuiteAccessTokenEntity, EXPIRE_TIME.intValue());
                    redisUtils.set(RedisKeyConstant.WX_CP_TP_EXPIRE_IN.concat(suiteId), System.currentTimeMillis() + newSuiteAccessTokenEntity.getExpiresIn() * 1000);
                }
            } catch (WxErrorException ex) {
                throw new BusinessException("获取suiteAccessToken 出错");
            }
        }

    }
    /**
     * 跟新授权Token
     *
     * @param suiteId
     * @param wxCpTpService
     */
    private void checkAndUpdateAuthorizeAccessToken(WxCpTpService wxCpTpService, String suiteId, String signature, String timestamp, String nonce) throws Exception{
        List<OpenAuthDTO> wxOpenAuthDTOS = queryWxOpenAuthListByComponentID(suiteId);
        if(Collections3.isNotEmpty(wxOpenAuthDTOS)) {
            wxOpenAuthDTOS.stream().forEach(wxOpenAuthDTO -> {
                try {
                    checkAndUpdateWxCpTpGlobalOpenAuthParam(wxCpTpService, wxOpenAuthDTO, signature, timestamp, nonce);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    /**
     * 跟新授权Token
     *
     * @param wxCpTpService
     */
    private void checkAndUpdateWxCpTpGlobalOpenAuthParam(WxCpTpService wxCpTpService, OpenAuthDTO wxOpenAuthDTO, String signature, String timestamp, String nonce)  throws Exception{
        //更新global OpenAuth
        if (null != wxOpenAuthDTO) {
            OpenAuthOfExtend openAuthOfExtend = wxOpenAuthDTO.getOpenAuthOfExtend();
            if(openAuthOfExtend == null) throw new BusinessException("读取三方应用配置参数openAuthOfExtend出错！");
            OpenAuthOfWxCpTp openAuthOfWxCpTp = openAuthOfExtend.getOpenAuthOfWxCpTp();
            if(openAuthOfWxCpTp == null) throw new BusinessException("读取三方应用配置参数OpenAuthOfWxCpTp出错！");
            openAuthOfWxCpTp.setSignature(signature);
            openAuthOfWxCpTp.setTimestamp(timestamp);
            openAuthOfWxCpTp.setNonceStr(nonce);
            String permanentCode = openAuthOfWxCpTp.getPermanentCode();
            String appId = wxOpenAuthDTO.getAppId();
            String suiteId = wxOpenAuthDTO.getComponentAppId();

            WxCpTpConfigStorage wxCpTpConfigStorage = wxCpTpService.getWxCpTpConfigStorage();
            String suiteAccessToken = wxCpTpConfigStorage.getSuiteAccessToken();

            String suiteTicket = wxCpTpConfigStorage.getSuiteTicket();
            Boolean needUpdateAccessTokenInDb = false;
            Object oldCorpAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_TP_CORP_ACCESS.concat(suiteId).concat(":").concat(appId));
            if(ObjectUtils.isEmpty(oldCorpAccessTokenObj) ) {
                WxAccessToken newCorpAccessTokenEntity = wxCpTpService.getCorpToken(appId, permanentCode, true);
                if (newCorpAccessTokenEntity != null) {
                    wxCpTpConfigStorage.updateAccessToken(appId, newCorpAccessTokenEntity.getAccessToken(), newCorpAccessTokenEntity.getExpiresIn());
                    redisUtils.set(RedisKeyConstant.WX_CP_TP_CORP_ACCESS.concat(suiteId).concat(":").concat(appId), newCorpAccessTokenEntity, EXPIRE_TIME);
                    String newJsapiTicketOfSuite = wxCpTpService.getSuiteJsApiTicket(appId, true);
                    if(StringUtils.isNotEmpty(newJsapiTicketOfSuite)){
                        wxCpTpConfigStorage.updateAuthSuiteJsApiTicket(appId, newJsapiTicketOfSuite, newCorpAccessTokenEntity.getExpiresIn());
                    }
                    String newJsapiTicketOfApp = wxCpTpService.getAuthCorpJsApiTicket(appId, true);
                    if(StringUtils.isNotEmpty(newJsapiTicketOfApp)){
                        wxCpTpConfigStorage.updateAuthCorpJsApiTicket(appId, newJsapiTicketOfApp, newCorpAccessTokenEntity.getExpiresIn());
                    }
                    needUpdateAccessTokenInDb = true;
                }

             }else{
                Long corpAccessTokenExpiredIn = openAuthOfWxCpTp.getCorpAccessExpirein();
                if (corpAccessTokenExpiredIn == null) corpAccessTokenExpiredIn = System.currentTimeMillis();
                if ((corpAccessTokenExpiredIn - System.currentTimeMillis()) <= 600 * 1000) {
                    WxAccessToken newCorpAccessTokenEntity = wxCpTpService.getCorpToken(appId, permanentCode, true);
                    if (newCorpAccessTokenEntity != null) {
                        wxCpTpConfigStorage.updateAccessToken(appId, newCorpAccessTokenEntity.getAccessToken(), newCorpAccessTokenEntity.getExpiresIn());
                        redisUtils.set(RedisKeyConstant.WX_CP_TP_CORP_ACCESS.concat(suiteId).concat(":").concat(appId), newCorpAccessTokenEntity, EXPIRE_TIME);
                        String newJsapiTicketOfSuite = wxCpTpService.getSuiteJsApiTicket(appId, true);
                        if(StringUtils.isNotEmpty(newJsapiTicketOfSuite)){
                            wxCpTpConfigStorage.updateAuthSuiteJsApiTicket(appId, newJsapiTicketOfSuite, newCorpAccessTokenEntity.getExpiresIn());
                        }
                        String newJsapiTicketOfApp = wxCpTpService.getAuthCorpJsApiTicket(appId, true);
                        if(StringUtils.isNotEmpty(newJsapiTicketOfApp)){
                            wxCpTpConfigStorage.updateAuthCorpJsApiTicket(appId, newJsapiTicketOfApp, newCorpAccessTokenEntity.getExpiresIn());
                        }
                        needUpdateAccessTokenInDb = true;
                    }
                }
            }
            //wxCpTpService.setWxCpTpConfigStorage(wxCpTpConfigStorage);
            LogUtils.info("=======WxCpTpConfigStorage:{}=========",JsonUtils.toJsonStr(wxCpTpConfigStorage));
            if (needUpdateAccessTokenInDb) {
                //LogUtils.info("\n begin Update WxCpTp OpenAuthParam：\n ");
                OpenAuthParam openAuthParam = BeanUtil.convertBean(wxOpenAuthDTO, OpenAuthParam.class);
                openAuthParam.setConfigType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode());
                openAuthParam.setConfigSubType(WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());
                if (StringUtils.isNotEmpty(suiteTicket))
                    openAuthOfWxCpTp.setSuiteTicket(suiteTicket);

                if (StringUtils.isNotEmpty(suiteAccessToken)) {
                    WxAccessToken suiteAccessTokenEntity = wxCpTpConfigStorage.getSuiteAccessTokenEntity();
                    openAuthOfWxCpTp.setSuiteAccessToken(suiteAccessTokenEntity.getAccessToken());
                    openAuthOfWxCpTp.setSuiteAccessExpireTime(suiteAccessTokenEntity.getExpiresIn());
                    openAuthOfWxCpTp.setSuiteAccessExpirein(System.currentTimeMillis() + suiteAccessTokenEntity.getExpiresIn() * 1000);
                }
                String corpAccessToken = wxCpTpConfigStorage.getAccessToken(appId);
                if (StringUtils.isNotEmpty(corpAccessToken)) {
                    WxAccessToken corpAccessTokenEntity = wxCpTpConfigStorage.getAccessTokenEntity(appId);
                    openAuthOfWxCpTp.setCorpAccessToken(corpAccessTokenEntity.getAccessToken());
                    openAuthOfWxCpTp.setCorpAccessExpireTime(corpAccessTokenEntity.getExpiresIn());
                    openAuthOfWxCpTp.setCorpAccessExpirein(System.currentTimeMillis() + corpAccessTokenEntity.getExpiresIn() * 1000);
                }
                String suiteJsapiTicket = wxCpTpConfigStorage.getAuthSuiteJsApiTicket(appId);
                if (StringUtils.isNotEmpty(suiteJsapiTicket)) {
                    openAuthOfWxCpTp.setJsapiTicketOfSuite(suiteJsapiTicket);
                    openAuthOfWxCpTp.setJsapiTicketOfSuiteExpireTime(EXPIRE_TIME);
                    openAuthOfWxCpTp.setJsapiTicketOfSuiteExpirein(System.currentTimeMillis() + EXPIRE_TIME);
                }
                String appJsapiTicket = wxCpTpConfigStorage.getAuthCorpJsApiTicket(appId);
                if (StringUtils.isNotEmpty(appJsapiTicket)) {
                    openAuthOfWxCpTp.setJsapiTicketOfApp(appJsapiTicket);
                    openAuthOfWxCpTp.setJsapiTicketOfAppExpireTime(EXPIRE_TIME);
                    openAuthOfWxCpTp.setJsapiTicketOfAppExpirein(System.currentTimeMillis() + EXPIRE_TIME);
                }
                openAuthOfExtend.setOpenAuthOfWxCpTp(openAuthOfWxCpTp);
                openAuthParam.setOpenAuthOfExtend(openAuthOfExtend);
                LogUtils.info("\n update WxCpTp openAuthParam：\n{} ", JsonUtils.toJsonStr(openAuthParam));
                globalOpenAuthFeignClient.modifyAuth(openAuthParam);
            }
        }
    }

    private OssPolicyDto getOssPolicy() {
        ResponseResult<OssPolicyDto> ossPolicyResult = openFileFeignClient.policy();
        DataUtils.trueThrowException(!ResponseCodeEnum.SUCCESS.getCode().equals(ossPolicyResult.getCode()), ossPolicyResult.getMsg());
        return ossPolicyResult.getData();
    }
    /**
     * @return
     * @Author ibeeking
     * 返回公众号授权信息
     */
    private OpenAuthDTO queryWxOpenAuthByType(Long tenantId,  Integer appType) {
        OpenAuthQuery query = new OpenAuthQuery();
        query.setTenantId(tenantId);
        query.setConfigType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode());
        query.setConfigSubType(WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());
        query.setAppType(appType);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        return responseResult.getData();
    }

    private List<OpenAuthDTO> queryWxOpenAuthListByComponentID(String suiteId) {
        OpenAuthQuery query = new OpenAuthQuery();
        query.setComponentAppId(suiteId);
        ResponseResult<List<OpenAuthDTO>> responseResult = globalOpenFeignClient.queryOpenAuthList(query);
        return responseResult.getData();
    }

    private OpenAuthDTO queryWxOpenAuthListByComponentIdAndAppId(String suiteId,String appId) {
        OpenAuthQuery query = new OpenAuthQuery();
        query.setComponentAppId(suiteId);
        query.setAppId(appId);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        return responseResult.getData();
    }

    private OpenConfigDTO queryWxOpenConfigByType(Integer type,Integer subType) {
        OpenConfigQuery query = new OpenConfigQuery();
        query.setType(type);
        query.setSubType(subType);
        ResponseResult<OpenConfigDTO> responseResult = globalOpenFeignClient.queryOpenConfigOne(query);
        return responseResult.getData();
    }

    private OssPolicyDto getOssFilePolicy(){
        ResponseResult<OssPolicyDto> responseResult = openFileFeignClient.policy();
        return responseResult.getData();
    }
}
